<template>
  <Dialog v-model="dialogVisible" :title="title" :width="dialogWidth" class="custom-dialog">
    <div class="form-container">
      <el-form
        ref="formRef"
        :model="formData"
        :label-width="labelWidth"
        :rules="formRules"
        label-position="top"
        class="custom-form"
      >
        <el-form-item label="系统模块是否通用" prop="moduleIsPublic" class="form-item">
          <el-radio-group v-model="formData.moduleIsPublic" class="custom-radio-group">
            <el-radio value="1" :label="1" class="custom-radio">不通用</el-radio>
            <el-radio value="2" :label="2" class="custom-radio">通用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="标识名" prop="name" class="form-item">
          <el-input
            v-model="formData.name"
            maxlength="6"
            placeholder="请输入表示名(字段名称)"
            class="custom-input"
          ></el-input>
        </el-form-item>

        <el-form-item label="标识属性名称" prop="fieldName" class="form-item">
          <el-input
            maxlength="15"
            v-model.trim="formData.fieldName"
            placeholder="请输入标识属性名称(即标识英文简介如:name、age、sex)"
            class="custom-input"
          ></el-input>
        </el-form-item>

        <el-form-item label="标识类型" prop="fieldType" class="form-item">
          <el-select
            class="custom-select"
            clearable
            v-model="formData.fieldType"
            placeholder="请选择标识类型"
          >
            <el-option
              v-for="(dict, index) in getDictOptions(DICT_TYPE.CRM_FIELD_TYPE)"
              :key="index"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label="选项数据"
          required
          v-if="formData.fieldType == 'select'"
          class="form-item"
        >
          <div class="options-container">
            <div class="draggable-container">
              <draggable :list="optionsList" :options="dragConfig">
                <template #item="{ element: item, index }">
                  <div :key="index" class="option-item">
                    <el-input v-model="item.value" class="option-input">
                      <template #suffix>
                        <div class="option-actions">
                          <div class="drag-hook" title="拖拽排序">
                            <Icon icon="ep:grid" class="drag-icon" />
                          </div>
                          <el-icon
                            class="delete-icon"
                            @click="handleDelete(index)"
                            title="删除选项"
                          >
                            <Delete />
                          </el-icon>
                        </div>
                      </template>
                    </el-input>
                  </div>
                </template>
              </draggable>
            </div>
            <div class="add-option-container">
              <el-button class="add-option-btn" :icon="Plus" @click="handleAdd">
                添加新选项
              </el-button>
            </div>
          </div>
        </el-form-item>

        <el-form-item
          label="标识预览:"
          v-if="formData.fieldType && formData.name"
          class="form-item preview-item"
        >
          <div class="preview-container">
            <div class="preview-label">{{ formData.name }}:</div>
            <div class="preview-field">
              <el-input
                v-if="formData.fieldType == 'input'"
                class="preview-input"
                :placeholder="'请输入' + formData.name"
                disabled
              ></el-input>
              <el-input-number
                v-if="formData.fieldType == 'number'"
                :min="1"
                label="label"
                class="preview-number"
                disabled
              ></el-input-number>
              <el-date-picker
                v-if="formData.fieldType == 'time'"
                :placeholder="'请选择' + formData.name"
                type="datetime"
                class="preview-date"
                value-format="x"
                disabled
              />
              <el-select
                :placeholder="'请选择' + formData.name"
                v-if="formData.fieldType == 'select'"
                class="preview-select"
                disabled
              >
                <el-option
                  v-for="(item, index) in optionsList"
                  :key="index"
                  :label="item.value"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="标识描述" class="form-item">
          <el-input
            type="textarea"
            v-model="formData.description"
            placeholder="请输入标识描述、备注等"
            rows="2"
            class="custom-textarea"
          ></el-input>
        </el-form-item>

        <el-form-item
          label="是否必填(新增、更新数据时是否必传)"
          prop="isRequired"
          class="form-item"
        >
          <el-radio-group v-model="formData.isRequired" class="custom-radio-group">
            <el-radio value="1" :label="1" class="custom-radio">必填</el-radio>
            <el-radio value="0" :label="0" class="custom-radio">非必填</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="列表是否显示(表格是否展示)" prop="isShow" class="form-item">
          <el-radio-group v-model="formData.isShow" class="custom-radio-group">
            <el-radio value="1" :label="1" class="custom-radio">是</el-radio>
            <el-radio value="0" :label="0" class="custom-radio">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="是否查询(高级筛选是否增加此字段)" prop="isSearch" class="form-item">
          <el-radio-group v-model="formData.isSearch" class="custom-radio-group">
            <el-radio value="1" :label="1" class="custom-radio">是</el-radio>
            <el-radio value="0" :label="0" class="custom-radio">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit" :disabled="formLoading" class="submit-btn">
          确 定
        </el-button>
        <el-button @click="dialogVisible = false" class="cancel-btn">取 消</el-button>
      </div>
    </template>
  </Dialog>
</template>

<script setup>
import draggable from 'vuedraggable'
import { DICT_TYPE, getDictOptions } from '@/utils/dict'
import * as customFieldApi from '@/api/crm/module/index.ts'
const { t } = useI18n()
import { Plus, Delete } from '@element-plus/icons-vue'
import { guid } from '@/utils/types.ts'

defineOptions({
  name: 'FormTable'
})
const formRules = reactive({
  moduleIsPublic: [{ required: true, message: '请选择通用以及不通用', trigger: 'change' }],
  name: [{ required: true, message: '请输入标识名(字段名称)', trigger: 'blur' }],
  fieldName: [
    { required: true, message: '请输入标识属性名称', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        const englishRegex = /^[^\u4e00-\u9fa5]+$/
        if (!englishRegex.test(value)) {
          callback(new Error('只能输入英文，不能输入中文'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  fieldType: [{ required: true, message: '请选择字段类型', trigger: 'change' }],
  isRequired: [{ required: true, message: '请选择是否必填', trigger: 'change' }],
  isShow: [{ required: true, message: '请选择列表是否显示', trigger: 'change' }],
  isSearch: [{ required: true, message: '请选择是否查询', trigger: 'change' }]
})
const formRef = ref(null)
const title = ref('新增')
const dialogVisible = ref(false)
const formData = reactive({
  moduleId: '', //模块id
  moduleIsPublic: '', //1通 2 不
  tableType: '', //所属表单
  name: '', //字段名称
  fieldName: '', //字段属性名称
  fieldType: '', //字段类型
  expansion: '', //拓展数据
  isRequired: '', //是否必填
  isShow: '', //列表是否显示
  isSearch: '', //是否查询
  description: '',
  id: ''
})
const optionsList = ref([])

// 响应式计算属性
const dialogWidth = computed(() => {
  return window.innerWidth <= 768 ? '95%' : '35%'
})

const labelWidth = computed(() => {
  return window.innerWidth <= 768 ? '100px' : '120px'
})

const dragConfig = computed(() => {
  return {
    group: guid(),
    forceFallback: false,
    fallbackClass: 'draggingStyle',
    handle: '.drag-hook',
    filter: '.el-input__inner',
    preventOnFilter: false
  }
})
const getAddValue = (index) => {
  const findRes = optionsList.value.find((o) => o.value === `选${index}`)
  if (findRes) {
    return getAddValue(index + 1)
  }
  return `选${index}`
}
// 添加新选项
const handleAdd = () => {
  const val = getAddValue(optionsList.value.length + 1)
  optionsList.value.push({
    value: val
  })
}
// 删除
const handleDelete = (index) => {
  optionsList.value.splice(index, 1)
}
// options 有没有重复的数据
const hasDuplicates = computed(() => {
  // 创建一个 Set 来存储已经出现过的值
  const valuesSet = new Set()
  // 遍历数组中的每个对象
  for (const item of optionsList.value) {
    // 检查当前对象的 value 属性是否已经在 Set 中
    if (valuesSet.has(item.value)) {
      // 如果存在，则说明有重复数据，返回 true
      return true
    }
    // 如果不存在，则将当前对象的 value 属性添加到 Set 中
    valuesSet.add(item.value)
  }
  // 遍历完整个数组都没有发现重复数据，返回 false
  return false
})
const emit = defineEmits(['success'])
const formLoading = ref(false)
const handleSubmit = async () => {
  await formRef.value.validate()
  formLoading.value = true
  try {
    if (formData.fieldType == 'select' && optionsList.value.length == 0) {
      ElMessage.warning('请检查选项数据')
      return
    }
    if (formData.fieldType == 'select' && hasDuplicates.value) {
      ElMessage.warning('选项数据不能重复数据')
      return
    }
    if (formData.fieldType == 'select') {
      const arr = []
      optionsList.value.map((item) => {
        arr.push(item.value)
      })
      formData.expansion = arr.join(',')
    }
    if (formType.value == 'create') {
      await customFieldApi.customFieldHeadCreate(formData)
      ElMessage.success(t('common.createSuccess'))
    } else {
      await customFieldApi.customFieldHeadUpdate(formData)
      ElMessage.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}
const formType = ref('')
const open = (type, item, moduleId, tableType) => {
  dialogVisible.value = true
  refreshVal()
  formData.tableType = tableType
  formData.moduleId = moduleId
  formType.value = type
  if (item) {
    const {
      moduleIsPublic,
      name,
      fieldName,
      fieldType,
      expansion,
      isRequired,
      isShow,
      isSearch,
      description,
      id
    } = item
    if (expansion) {
      expansion.split(',').map((item) => {
        optionsList.value.push({
          value: item
        })
      })
    }
    Object.assign(formData, {
      moduleIsPublic,
      name,
      fieldName,
      fieldType,
      isRequired,
      isShow,
      isSearch,
      description,
      id
    })
  }
  if (type == 'create') {
    title.value = '新增'
  } else {
    title.value = '编辑'
  }
}
defineExpose({ open })
const refreshVal = () => {
  optionsList.value = []
  formData.moduleIsPublic = ''
  formData.name = ''
  formData.fieldName = ''
  formData.fieldType = ''
  formData.expansion = ''
  formData.isRequired = ''
  formData.isShow = ''
  formData.isSearch = ''
  formData.description = ''
  formData.id = ''
}
</script>

<style scoped>
/* 对话框样式 */
.custom-dialog :deep(.el-dialog) {
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
}

.custom-dialog :deep(.el-dialog__header) {
  background: linear-gradient(135deg, #0052cc 0%, #003d99 100%);
  color: white;
  padding: 20px 24px;
  border-radius: 12px 12px 0 0;
}

.custom-dialog :deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
  font-size: 16px;
}

.custom-dialog :deep(.el-dialog__headerbtn .el-dialog__close) {
  color: white;
  font-size: 18px;
}

.custom-dialog :deep(.el-dialog__headerbtn .el-dialog__close:hover) {
  color: #f0f7ff;
}

.custom-dialog :deep(.el-dialog__body) {
  padding: 24px;
  background: #fafbfc;
  max-height: 70vh;
  overflow-y: auto;
}

/* 表单容器 */
.form-container {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.custom-form {
  margin: 0;
}

.form-item {
  margin-bottom: 20px;
}

.form-item :deep(.el-form-item__label) {
  color: #303133;
  font-weight: 600;
  line-height: 1.5;
  margin-bottom: 8px;
}

/* 输入框样式 */
.custom-input {
  width: 100%;
}

.custom-input :deep(.el-input__wrapper.is-focus) {
  border-color: #0052cc;
  box-shadow: 0 0 0 1px #0052cc inset;
}

/* 选择器样式 */
.custom-select {
  width: 100%;
}

.custom-select :deep(.el-input__wrapper.is-focus) {
  border-color: #0052cc;
  box-shadow: 0 0 0 1px #0052cc inset;
}

/* 文本域样式 */
.custom-textarea :deep(.el-textarea__inner:focus) {
  border-color: #0052cc;
  box-shadow: 0 0 0 1px #0052cc inset;
}

/* 单选框组样式 */
.custom-radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.custom-radio {
  margin-right: 0;
  padding: 8px 16px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  transition: all 0.3s ease;
  background: white;
}

.custom-radio:hover {
  border-color: #0052cc;
  background: #f0f7ff;
}

.custom-radio :deep(.el-radio__input.is-checked .el-radio__inner) {
  background-color: #0052cc;
  border-color: #0052cc;
}

.custom-radio :deep(.el-radio__input.is-checked + .el-radio__label) {
  color: #0052cc;
  font-weight: 600;
}

.custom-radio.is-checked {
  border-color: #0052cc;
  background: #f0f7ff;
}

/* 选项数据容器 */
.options-container {
  width: 100%;
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  border: 1px solid #e4e7ed;
}

.draggable-container {
  margin-bottom: 12px;
}

.option-item {
  margin: 8px 0;
  position: relative;
}

.option-input {
  width: 100%;
}

.option-input :deep(.el-input__wrapper.is-focus) {
  border-color: #0052cc;
  box-shadow: 0 0 0 1px #0052cc inset;
}

.option-actions {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 0 8px;
}

.drag-hook {
  cursor: move;
  display: flex;
  align-items: center;
  color: #909399;
  transition: color 0.3s ease;
}

.drag-hook:hover {
  color: #0052cc;
}

.drag-icon {
  font-size: 14px;
}

.delete-icon {
  cursor: pointer;
  color: #f56c6c;
  font-size: 14px;
  transition: all 0.3s ease;
}

.delete-icon:hover {
  color: #f78989;
  transform: scale(1.1);
}

.add-option-container {
  display: flex;
  justify-content: center;
}

.add-option-btn {
  background: #0052cc;
  border-color: #0052cc;
  color: white;
  padding: 8px 16px;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.add-option-btn:hover {
  background: #003d99;
  border-color: #003d99;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 82, 204, 0.3);
}

/* 预览区域 */
.preview-item {
  background: #f0f7ff;
  border-radius: 8px;
  padding: 16px;
  border: 1px solid #b3d8ff;
}

.preview-container {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.preview-label {
  font-weight: 600;
  color: #0052cc;
  min-width: 60px;
  flex-shrink: 0;
}

.preview-field {
  flex: 1;
  min-width: 200px;
}

.preview-input,
.preview-number,
.preview-date,
.preview-select {
  width: 100%;
}

/* 对话框底部 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 24px;
  background: #fafbfc;
  border-radius: 0 0 12px 12px;
  border-top: 1px solid #e4e7ed;
}

.submit-btn {
  padding: 8px 20px;
  border-radius: 6px;
  background: #0052cc;
  border-color: #0052cc;
  font-weight: 600;
  transition: all 0.3s ease;
}

.submit-btn:hover {
  background: #003d99;
  border-color: #003d99;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 82, 204, 0.3);
}

.submit-btn:active {
  transform: translateY(0);
}

.cancel-btn {
  padding: 8px 20px;
  border-radius: 6px;
  background: #f5f7fa;
  border-color: #dcdfe6;
  color: #606266;
  font-weight: 500;
  transition: all 0.3s ease;
}

.cancel-btn:hover {
  background: #ecf5ff;
  border-color: #0052cc;
  color: #0052cc;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .custom-dialog :deep(.el-dialog) {
    width: 95% !important;
    margin: 5vh auto;
  }

  .custom-dialog :deep(.el-dialog__header) {
    padding: 16px 20px;
  }

  .custom-dialog :deep(.el-dialog__body) {
    padding: 16px;
    max-height: 60vh;
  }

  .form-container {
    padding: 16px;
  }

  .form-item {
    margin-bottom: 16px;
  }

  .custom-radio-group {
    flex-direction: column;
    gap: 8px;
  }

  .custom-radio {
    width: 100%;
    text-align: center;
  }

  .preview-container {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .preview-label {
    min-width: auto;
  }

  .preview-field {
    width: 100%;
    min-width: auto;
  }

  .dialog-footer {
    padding: 12px 16px;
    flex-direction: column;
  }

  .submit-btn,
  .cancel-btn {
    width: 100%;
  }

  .options-container {
    padding: 12px;
  }
}

@media (max-width: 480px) {
  .custom-dialog :deep(.el-dialog) {
    width: 98% !important;
    margin: 2vh auto;
  }

  .custom-dialog :deep(.el-dialog__header) {
    padding: 12px 16px;
  }

  .custom-dialog :deep(.el-dialog__title) {
    font-size: 14px;
  }

  .custom-dialog :deep(.el-dialog__body) {
    padding: 12px;
    max-height: 50vh;
  }

  .form-container {
    padding: 12px;
  }

  .options-container {
    padding: 8px;
  }
}

/* 加载状态优化 */
.el-loading-mask {
  background-color: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(2px);
}

/* 滚动条美化 */
.custom-dialog :deep(.el-dialog__body)::-webkit-scrollbar {
  width: 6px;
}

.custom-dialog :deep(.el-dialog__body)::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.custom-dialog :deep(.el-dialog__body)::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.custom-dialog :deep(.el-dialog__body)::-webkit-scrollbar-thumb:hover {
  background: #0052cc;
}

/* 动画效果 */
.form-container {
  transition: all 0.3s ease;
}

.option-item,
.custom-radio {
  transition: all 0.3s ease;
}

/* 主题色变量 */
:root {
  --primary-color: #0052cc;
  --primary-hover: #003d99;
  --primary-light: #f0f7ff;
  --border-color: #e4e7ed;
  --text-color: #303133;
  --bg-color: #f8f9fa;
}

/* Element Plus 组件样式覆盖 */
:deep(.el-select-dropdown__item.is-selected) {
  color: #0052cc;
  font-weight: 600;
}

:deep(.el-select-dropdown__item:hover) {
  background-color: #f0f7ff;
}

:deep(.el-input-number .el-input__inner) {
  text-align: left;
}

/* 拖拽样式 */
.draggingStyle {
  opacity: 0.8;
  transform: rotate(5deg);
}
</style>
